package com.tiny.thread.executor;

import java.util.concurrent.*;

/**
 * Demo1：线程池的创建
 * Created by zhumenglong on 2017/3/11.
 */
public class Demo1 {

    /**
     * ExecutorService创建线程池
     */
    public static void method1() {
        // 一个有7个作业线程的线程池，老大的老大找到一个管7个人的小团队的老大
        ExecutorService boss = Executors.newFixedThreadPool(7);
        //提交作业给老大，作业内容封装在Callable中，约定好了输出的类型是String。
        try {
            String outputs = boss.submit(
                    () -> {
                        return "I am a task, which submited by the so called laoda, and run by those anonymous workers";
                    }
            ).get();
            System.out.println(outputs);
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
    }

    /**
     * 实现一个支持定时及周期性的任务执行的线程池，多数情况下可用来替代Timer类。
     */
    public static void method2() {
        Executor executor = Executors.newFixedThreadPool(10);
        Runnable task =()->System.out.println("task over");
        executor.execute(task);
        executor = Executors.newScheduledThreadPool(10);
        ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;
        scheduler.scheduleAtFixedRate(task, 10, 10, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        method2();
    }
}
